package com.ourteam.system.api;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ourteam.frame.controller.AbstractServiceController;
import com.ourteam.system.domain.SystemNotifyConfigBean;
import com.ourteam.system.service.ISystemNotifyConfigService;

@Controller
@CrossOrigin
@RequestMapping("/api/notice")
public class SystemNoticeAPI extends AbstractServiceController {

	@Autowired
	private ISystemNotifyConfigService NOTICE_SERVICE;

	private static final Map<String, AbstractNoticeListener> NOTICE_MAP = new HashMap<>();

	@RequestMapping("/getSystemNotices")
	@ResponseBody
	public SystemNoticeBean[] getSystemNotices(HttpServletRequest request, Model model) throws Exception {

		SystemNotifyConfigBean[] notifyConfigBeans = NOTICE_SERVICE.getSystemNotifyConfigs();

		SystemNoticeBean[] noticeBeans = new SystemNoticeBean[notifyConfigBeans.length];

		for (int i = 0; i < notifyConfigBeans.length; i++) {
			SystemNotifyConfigBean systemNotifyConfigBean = notifyConfigBeans[i];

			SystemNoticeBean noticeBean = new SystemNoticeBean();

			noticeBean.setId(systemNotifyConfigBean.getNotifyName());

			noticeBean.setNoticeIcon(systemNotifyConfigBean.getNotifyIcon());

			noticeBean.setNoticeTitle(systemNotifyConfigBean.getNotifyMessage());

			noticeBean.setViewPath(systemNotifyConfigBean.getViewPath());

			String noticeListener = systemNotifyConfigBean.getNotifyListener();

			if (StringUtils.isNotBlank(noticeListener)) {

				if (NOTICE_MAP.containsKey(noticeListener) == false) {
					NOTICE_MAP.put(noticeListener,
							(AbstractNoticeListener) Class.forName(noticeListener).newInstance());
				}

				int countInfo = NOTICE_MAP.get(noticeListener).getNoticeCountInfo(getLoginUserId());

				noticeBean.setNoticeCount(countInfo);

			} else {
				noticeBean.setNoticeCount(0);
			}

			noticeBeans[i] = noticeBean;

		}

		return noticeBeans;
	}

}
